﻿using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using FlickrSample.SL.Infrastructure.Flickr;
using FlickrSample.SL.Infrastructure.Flickr.Commands;
using FlickrSample.SL.Infrastructure.Repo.Download;

namespace FlickrSample.SL.Infrastructure.Repo.Flickr.Online
{
    public class FlickrRepo : IFlickrRepo
    {
        const string BASE_PATH = "http://api.flickr.com/services/rest/?";

        const string apiKey = "5e78122b793cead3296cf299fc320b72";

        private IWebDownloader downloader;

        public FlickrRepo(IWebDownloader downloader)
        {
            this.downloader = downloader;
        }

        public void ExecuteCommand(IFlickrCommand command, Action<string> completeCallback)
        {
            var uri = getRequestUri(command);
            
            downloader.DownloadData(uri, (stream) =>
                                             {
                                                 if (stream != null && stream.Length > 0)
                                                 {
                                                     using (var sr = new StreamReader(stream))
                                                     {
                                                         completeCallback(sr.ReadToEnd());
                                                         sr.Close();
                                                     }

                                                 }
                                                 else
                                                 {
                                                     completeCallback(null);
                                                 }
                                             });
        }


        Uri getRequestUri(IFlickrCommand command)
        {
            string uriString = String.Format("{0}method={1}&api_key={2}", BASE_PATH, command.MethodName, apiKey);
            foreach (string key in command.Parameters.Keys)
            {
                uriString += string.Format("&{0}={1}", key, command.Parameters[key]);
            }

            return new Uri(uriString, UriKind.Absolute);
        }
    }
}
